var app = getApp();
var common = require('../../utils/common');
var server = require('../../utils/server');
var amapFile = require('../../libs/amap-wx.js');
Page({
  data: {
    userInfo: '',
    isLocate: true,
    userFace: "",
    cartNum: 0,
    showPhonePop: false,
    showLoginPop: false,
    isLogin: true,
    isRegister: true,
    isDisableLog: false,
    isDisableReg: false,
    isSTTVip: false
  },
  onShow() {
    app.globalData.refreshTag = app.globalData.isChangeIndexLocation ? true : false;
    if (app.globalData.wxversion <= 700) {
      wx.setNavigationBarColor({
        frontColor: '#fff',
        backgroundColor: '#36D147'
      })
    }
    this.setData({
      isLocate: app.globalData.isLocate
    })
    if (app.globalData.isLocate) {
      this.locateCur();
    }
  },
  onHide() {},
  locateCur() {
    var that = this;
    if (app.globalData.locateCity != "") {
      that.getUserInfo();
    } else {
      var gdMap = new amapFile.AMapWX({
        key: common.gdKey
      });
      gdMap.getRegeo({
        success: resp => {
          that.data.city = resp[0].regeocodeData.addressComponent.city;
          app.globalData.locateLongitude = resp[0].longitude;
          app.globalData.locateLatitude = resp[0].latitude;
          app.globalData.locateCity = resp[0].regeocodeData.addressComponent.city;
          app.globalData.locateProvince = resp[0].regeocodeData.addressComponent.province;
          that.getUserInfo();
        },
        fail: info => {
          that.setData({
            isLocate: false,
            showLoginPop: false
          })
          app.globalData.isLocate = false
        }
      })
    }
    wx.stopPullDownRefresh();
  },
  //获取用户信息
  getUserInfo() {
    wx.login({
      success: resp => {
        wx.getUserInfo({
          success: res => {
            this.setData({
              showLoginPop: false
            })
            var code = resp.code,
              that = this,
              userParams = {
                "js_code": code,
                "encryptedData": res.encryptedData,
                "iv": res.iv,
                "userinfo": res.userInfo,
                "longitude": app.globalData.locateLongitude,
                "latitude": app.globalData.locateLatitude,
                "province": app.globalData.locateProvince,
                "city": app.globalData.locateCity,
                "scene": ''
              };
            server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
              if (res.data.errno == "0") {
                that.setData({
                  isLogin: true
                })
                wx.setStorage({
                  key: "sso",
                  data: res.data.data.sso,
                  success: ret => {
                    app.globalData.isGetWxUserinfo = true;
                    if (JSON.stringify(res.data.data.member) == "{}") {
                      that.setData({
                        isRegister: false
                      })
                      console.log('未登录')
                    } else if (JSON.stringify(res.data.data.member) != "{}") {
                      that.setData({
                        showPhonePop: false,
                        isRegister: true
                      })
                      that.setData({
                        userInfo: res.data.data
                      })
                      that.getCartNum();
                      that.storageUserinfo(res.data.data);
                    }
                    that.getOrderStatus();
                  }
                })
              } else {
                common.showErrorToast(res.data.errmsg);
              }
            })
          },
          fail: res => {
            wx.removeStorage({
              key: 'userInfo',
              success: function (res) {
                console.log(res.data)
              }
            })
            this.setData({
              isLogin: false
            })
          }
        })
      },
      fail: res => {
        this.setData({
          isLogin: false
        })
      }
    })
  },
  getOrderStatus() {
    server.postJSON(common.storePath + 'order/lists/', {
      "status_select": 'nopay',
      "page": 1,
      "count": 10
    }, res => {
      if (res.data.errno == "0") {
        if (res.data.data.length > 0) {
          this.setData({
            hasNOPayOrder: true
          })
        } else {
          this.setData({
            hasNOPayOrder: false
          })
        }

      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  //授权用户信息
  login(e) {
    this.setData({
      isDisableLog: true
    })
    if (e.detail.errMsg == "getUserInfo:ok") {
      this.setData({
        showLoginPop: false,
        isLogin: true
      })
      var that = this
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              var code = resp.code,
                that = this,
                userParams = {
                  "js_code": code,
                  "encryptedData": res.encryptedData,
                  "iv": res.iv,
                  "userinfo": res.userInfo,
                  "longitude": app.globalData.locateLongitude,
                  "latitude": app.globalData.locateLatitude,
                  "province": app.globalData.locateProvince,
                  "city": app.globalData.locateCity,
                  "scene": ''
                }
              server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
                if (res.data.errno == "0") {
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: ret => {
                      that.setData({
                        isDisableLog: false
                      })
                      app.globalData.isGetWxUserinfo = true;
                      if (JSON.stringify(res.data.data.member) == "{}") {
                        that.setData({
                          showPhonePop: true,
                          isRegister: false
                        })
                      } else if (JSON.stringify(res.data.data.member) != "{}") {
                        that.setData({
                          userInfo: res.data.data,
                          isRegister: true
                        })
                        that.getCartNum();
                        that.storageUserinfo(res.data.data)
                      }
                    }
                  })
                } else {
                  that.setData({
                    isDisableLog: false
                  })
                  common.showErrorToast(res.data.errmsg)
                }
              })
            }
          })
        }
      })
    } else {
      this.setData({
        isLogin: false,
        isDisableLog: false
      })
      wx.showToast({
        icon: 'none',
        title: '需要授权用户信息使用元初到家！'
      })
    }
  },

  goToAddress: function () {
    this.checkLogin('../../address_manage/pages/addrIndex')
  },
  callServer() {
    wx.makePhoneCall({
      phoneNumber: common.serverTel
    })
  },
  // 打开定位
  openLocation(e) {
    if (e.detail.errMsg == "openSetting:ok" && e.detail.authSetting['scope.userLocation']) {
      app.globalData.isLocate = true;
      wx.switchTab({
        url: '../index/index',
      })
    } else {
      common.showErrorToast('需要授权地理位置后使用！');
    }
  },
  goToMemberCard() {
    this.checkLogin('../memberCard/memberCardIndex')
  },
  goToActivity() {
    wx.navigateTo({
      url: '../activity/activity'
    })
  },
  alertTel() {
    wx.navigateTo({
      url: '../common/register',
    })

  },
  //授权手机号
  getPhoneNumber: function (e) {
    var that = this;
    this.setData({
      isDisableReg: true
    })
    if (e.detail.errMsg != "getPhoneNumber:ok") {
      wx.showToast({
        icon: 'none',
        title: '需要授权手机号后使用元初到家！',
      })
      this.setData({
        isDisableReg: false
      })
    } else {
      var that = this;
      wx.login({
        success: res => {
          this.setData({
            showPhonePop: false
          });
          server.postJSON(common.basePath + 'miniprogram/registermember/', {
            "iv": e.detail.iv,
            "encryptedData": e.detail.encryptedData,
            "js_code": res.code,
            "city": app.globalData.locateCity
          }, res => {
            if (res.data.errno == '0') {
              that.setData({
                userInfo: res.data.data,
                isRegister: true,
                isDisableReg: false
              })
              that.getCartNum();
              that.getOrderStatus();
              that.storageUserinfo(res.data.data)
            } else {
              this.setData({
                isDisableReg: false
              })
              common.showErrorToast(res.data.errmsg);
            }
          })
        },
        fail: res => {
          this.setData({
            isDisableReg: false
          })
        }
      })
    }
  },
  showCheckTel() {
    wx.navigateTo({
      url: '../common/register',
    })
    this.setData({
      showPhonePop: false
    })
  },
  //本地存储用户信息
  storageUserinfo(data) {
    wx.setStorage({
      key: "userInfo",
      data: data
    })
    this.checkSttVip()
  },
  checkSttVip() {
    server.postJSON(common.basePath + 'vip/level/', '', res => {
      if (res.data.errno == '0') {
        this.setData({
          isSTTVip: res.data.data.level > 0 ? true : false
        })
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  // 电子发票
  downloadInvoice() {
    wx.navigateTo({
      url: 'electronicInvoice',
    })
  },
  aboutUs() {
    wx.navigateTo({
      url: '../common/gzh?url=https://mp.weixin.qq.com/s/4dXlzR0_YPUql1plIQDQ8w',
    })
  },
  goToTickets() {
    var url = 'userVouchers';
    this.checkLogin(url)
  },
  //获取购物车数量
  getCartNum() {
    wx.getStorage({
      key: 'storeId',
      success: resp => {
        server.postJSON(common.storePath + 'cart/goodsnum', {
          "store_id": resp.data,
          "is_deliverable": 0
        }, res => {
          if (res.data.errno == "0") {
            this.setData({
              cartNum: res.data.data.cart.num
            })
          } else {
            common.showErrorToast(res.data.errmsg);
          }
        })
      },
    })

  },
  goToCreditDetail() {
    var url = '';
    if (this.data.userInfo != '') {
      url = '../memberCard/memberScoreDetail?tel=' + this.data.userInfo.member.cellphone
    } else {
      url = '../memberCard/memberScoreDetail?tel='
    }
    this.checkLogin(url)
  },
  goToOrdercenter(e) {
    var status = e.currentTarget.dataset.status;
    app.globalData.searchOrderStatus = status;
    if (this.data.isLogin && this.data.isRegister) {
      wx.switchTab({
        url: '../order/orderIndex'
      })
    } else if (!this.data.isLogin) {
      this.setData({
        showLoginPop: true
      })
    } else if (!this.data.isRegister) {
      this.setData({
        showPhonePop: true
      })
    }

  },
  showLoginPop() {
    this.setData({
      showLoginPop: true
    })
  },
  showPhonePop() {
    this.setData({
      showPhonePop: true
    })
  },
  hideLoginPop() {
    this.setData({
      showLoginPop: false
    })
  },
  goToMemberIndex() {
    this.checkLogin('../../pages/memberCard/memberCardIndex')
  },
  hidePhonePop() {
    this.setData({
      showPhonePop: false
    })
  },
  goToCart() {
    if (this.data.isLogin && this.data.isRegister) {
      app.globalData.cartIndexType = 1;
      wx.switchTab({
        url: '../cart/cartIndex',
      })
    } else if (!this.data.isLogin) {
      this.setData({
        showLoginPop: true
      })
    } else if (!this.data.isRegister) {
      this.setData({
        showPhonePop: true
      })
    }
  },
  showAgreement() {
    wx.navigateTo({
      url: '../common/agreement',
    })
  },
  checkLogin(url) {
    if (this.data.isLogin && this.data.isRegister) {
      wx.navigateTo({
        url: url,
      })
    } else if (!this.data.isLogin) {
      this.setData({
        showLoginPop: true
      })
    } else if (!this.data.isRegister) {
      this.setData({
        showPhonePop: true
      })
    }
  },
  goToSTT() {
    wx.navigateTo({
      url: '../../membership_supply/pages/productListsM4',
    })
  }
})